package com.plm.maque.dao;

import com.plm.maque.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

/**
 * @author Limi
 * @create 2018-12-30 18:43
 */
@Component
public class UserDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建对象
     */
    public void saveUser(User user){
        mongoTemplate.save(user);
    }

    /**
     * 根据用户名查询对象
     */
    public User findByUsername(String username){
        Query query = new Query(Criteria.where("username").is(username));
        User user = mongoTemplate.findOne(query, User.class);
        return user;
    }

    /**
     * 根据用ID查询对象
     */
    public User findByUserId(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        return mongoTemplate.findOne(query, User.class);
    }

    /**
     * 更新对象
     */
    public void updateUser(User user){
        Query query = new Query(Criteria.where("userId").is(user.getUserId()));
        Update update = new Update().set("password", user.getPassword())
                    .set("mobile", user.getMobile());
        //更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query, update, User.class);
    }

    /**
     * 删除对象
     */
    public void deleteByUserId(Long userId){
        Query query = new Query(Criteria.where("userId").is(userId));
        mongoTemplate.remove(query, User.class);
    }

}
